<?php
/**
 * Created by PhpStorm.
 * User: candy
 * Date: 2017/3/13
 * Time: 上午12:25
 */

namespace app\index\controller;

use app\index\model\Collect;
use app\index\model\Program;
use think\Controller;
use app\index\model\Users;
use think\Db;

class Collects extends Controller
{
    // 收藏节目
    public function submitCollect($token, $program_id) {
        //token验证
        $user_id = checkToken($token);
        //判断节目是否存在
        if (Program::where('program_id',$program_id)->count() <= 0) {
            return myJson(-1, '收藏失败 - 节目不存在', '');
        }
        //判断是否已收藏
        if (Collect::where(['user_id' => $user_id, 'program_id' => $program_id])->count() > 0) {
            return myJson(-1, '收藏失败 - 该节目已收藏', '');
        }
        try {
            $collect = new Collect();
            $collect->program_id = $program_id;
            $collect->user_id = $user_id;
            $collect->collect_time = date('Y-m-d H:i:s');
            $collect->save();
            return myJson(1, '收藏成功', '');
        } catch (\Exception $e) {
            print_r('catch');
            return myJson(-1, '收藏失败 - ' . $e->getMessage(), '');
        }

    }

    //判断是否已收藏
    public function isCollect($token, $program_id) {
        //token验证
        $user_id = checkToken($token);
        //判断是否已收藏
        if (Collect::where(['user_id' => $user_id, 'program_id' => $program_id])->count() > 0) {
            return myJson(1, '已收藏', '');
        }
        return myJson(-1, '未收藏', '');
    }

    // 取消收藏
    public function cancelCollect($token, $program_id) {
        //token验证
        $user_id = checkToken($token);
        //判断是否已收藏
        $collect = new Collect();
        $result = $collect->where([
            'user_id' => $user_id,
            'program_id' => $program_id
        ])->find();
        if (count($result) <= 0) {
            return myJson(-1, '取消收藏失败 - 该节目还未收藏', '');
        }
        try {
            $result->delete();
            return myJson(1, '取消收藏成功', '');
        } catch (\Exception $e) {
            return myJson(-1, '取消收藏失败 - ' . $e->getMessage(), '');
        }
    }

    //我的收藏
    public function selectMyCollect($token, $page_index) {
        //token验证
        $user_id = checkToken($token);
        if (Collect::where('user_id', $user_id)->count() <= 0) {
            return myJson(-1, '还没有任何收藏', '');
        }

        // 逻辑处理
        $page_num = 10; //每次返回10条数据
        $start_index = ($page_index - 1) * $page_num;

        $result = Db::name('collect')
            ->alias('a')
            ->join('tv_program b', 'a.program_id = b.program_id')
            ->field('b.program_id, b.program_name, b.program_url, b.program_logo, b.program_type, a.collect_time')
            ->where('user_id', $user_id)
            ->limit($start_index, $page_num)
            ->order('collect_time', 'desc')
            ->select();

        if (!$result) {
            return myJson(1, '没有更多数据', '');
        }
        return myJson(1, '收藏列表', $result);
    }



}